<template>
    <v-container fluid>
        <v-card class="elevation-10">
            <!-- 搜索区域 -->
            <v-card-text class="pb-0">
                <v-row>
                    <v-col class="d-flex align-center" cols="12" md="3">
                        <v-btn v-if="$perms('customer_customerrelation_insert')" color="primary" prepend-icon="mdi-plus"
                            @click="handleAddRelation">
                            新增
                        </v-btn>
                        <div class="d-flex gap-2 ml-2">
                            <v-btn v-if="$perms('customer_customerrelation_import')" :disabled="!selectRows.length"
                                color="error" icon="mdi-delete" size="small" variant="outlined"
                                @click="handleDeleteBatch" />

                            <v-btn v-if="$perms('customer_customerrelation_export')" color="success" icon="mdi-download"
                                size="small" variant="outlined" @click="handleExport" />

                            <v-btn v-if="$perms('customer_customerrelation_export')" color="info" icon="mdi-upload"
                                size="small" variant="outlined" @click="handleImport" />
                        </div>
                    </v-col>
                    <v-col cols="12" md="2">
                        <v-text-field v-model="queryParams.customerQP!.phone_LIKE" clearable density="compact"
                            hide-details label="手机号查询" placeholder="输入家长手机号" prepend-inner-icon="mdi-phone"
                            variant="outlined" />
                    </v-col>
                    <v-col cols="12" md="2">
                        <v-text-field v-model="queryParams.customerQP!.name_LIKE" clearable density="compact"
                            hide-details label="家长姓名" placeholder="输入家长姓名" prepend-inner-icon="mdi-account"
                            variant="outlined" />
                    </v-col>
                    <v-col cols="12" md="2">
                        <v-text-field v-model="queryParams.studentQP!.name_LIKE" clearable density="compact"
                            hide-details label="学生姓名" placeholder="输入学生姓名" prepend-inner-icon="mdi-school"
                            variant="outlined" />
                    </v-col>
                    <v-col cols="12" md="3">
                        <div class="d-flex gap-2">
                            <v-btn color="primary" prepend-icon="mdi-magnify" variant="flat" @click="fetchData"> 查询
                            </v-btn>
                            <v-btn color="grey" prepend-icon="mdi-refresh" variant="outlined" @click="resetQuery"> 重置
                            </v-btn>
                            <v-btn variant="outlined" @click="toggleMoreQuery"> 更多</v-btn>
                        </div>
                    </v-col>
                </v-row>
            </v-card-text>

            <!-- 更多查询条件 -->
            <v-expand-transition>
                <v-card-text v-show="showMoreQuery" class="pt-0">
                    <v-divider class="mb-4"></v-divider>

                    <!-- 关系信息查询 -->
                    <div class="mb-4">
                        <h4 class="text-subtitle-1 font-weight-medium mb-3 text-primary">
                            <v-icon class="mr-2" size="16">mdi-account-group</v-icon>
                            关系信息
                        </h4>
                        <v-row>
                            <v-col cols="12" md="3">
                                <v-select v-model="queryParams.relationType_EQ" :items="dict['relation_type']" clearable
                                    density="compact" hide-details item-title="dictName" item-value="dictValue"
                                    label="关系类型" variant="outlined" />
                            </v-col>
                            <v-col cols="12" md="3">
                                <v-select v-model="queryParams.isPrimary_EQ" :items="dict['yes_no']" clearable
                                    density="compact" hide-details item-title="dictName" item-value="dictValue"
                                    label="主要联系人" variant="outlined" />
                            </v-col>
                            <v-col cols="12" md="3">
                                <v-select v-model="queryParams.sourceChannel_EQ" :items="channels.list" clearable
                                    density="compact" hide-details item-title="channelName" item-value="id" label="来源渠道"
                                    variant="outlined" />
                            </v-col>
                            <v-col cols="12" md="3">
                                <v-select v-model="queryParams.relationStatus_EQ" :items="dict['relation_status']"
                                    clearable density="compact" hide-details item-title="dictName"
                                    item-value="dictValue" label="关系状态" variant="outlined" />
                            </v-col>
                        </v-row>
                    </div>

                    <!-- 家长查询条件 -->
                    <div class="mb-4">
                        <h4 class="text-subtitle-1 font-weight-medium mb-3 text-primary">
                            <v-icon class="mr-2" size="16">mdi-account</v-icon>
                            家长信息
                        </h4>
                        <v-row>
                            <v-col cols="12" md="3">
                                <v-text-field v-model="queryParams.customerQP!.email_LIKE" clearable density="compact"
                                    hide-details label="家长邮箱" placeholder="输入家长邮箱" prepend-inner-icon="mdi-email"
                                    variant="outlined" />
                            </v-col>
                            <v-col cols="12" md="3">
                                <v-text-field v-model="queryParams.customerQP!.idCard_LIKE" clearable density="compact"
                                    hide-details label="身份证号" placeholder="输入身份证号"
                                    prepend-inner-icon="mdi-card-account-details" variant="outlined" />
                            </v-col>
                            <v-col cols="12" md="3">
                                <v-select v-model="queryParams.customerQP!.customerType_EQ"
                                    :items="dict['customer_type']" clearable density="compact" hide-details
                                    item-title="dictName" item-value="dictValue" label="客户类型" variant="outlined" />
                            </v-col>
                            <v-col cols="12" md="3">
                                <v-select v-model="queryParams.customerQP!.status_EQ" :items="dict['customer_status']"
                                    clearable density="compact" hide-details item-title="dictName"
                                    item-value="dictValue" label="客户状态" variant="outlined" />
                            </v-col>
                            <v-col cols="12" md="3">
                                <v-select v-model="queryParams.customerQP!.gender_EQ" :items="dict['gender']" clearable
                                    density="compact" hide-details item-title="dictName" item-value="dictValue"
                                    label="家长性别" variant="outlined" />
                            </v-col>
                            <v-col cols="12" md="3">
                                <v-text-field v-model="queryParams.customerQP!.address_LIKE" clearable density="compact"
                                    hide-details label="家长地址" placeholder="输入家长地址" prepend-inner-icon="mdi-map-marker"
                                    variant="outlined" />
                            </v-col>
                        </v-row>
                    </div>

                    <!-- 学生查询条件 -->
                    <div class="mb-4">
                        <h4 class="text-subtitle-1 font-weight-medium mb-3 text-primary">
                            <v-icon class="mr-2" size="16">mdi-school</v-icon>
                            学生信息
                        </h4>
                        <v-row>
                            <v-col cols="12" md="3">
                                <v-select v-model="queryParams.studentQP!.grade_EQ" :items="dict['student_grade']"
                                    clearable density="compact" hide-details item-title="dictName"
                                    item-value="dictValue" label="学生年级" variant="outlined" />
                            </v-col>
                            <v-col cols="12" md="3">
                                <v-select v-model="queryParams.studentQP!.status_EQ" :items="dict['student_status']"
                                    clearable density="compact" hide-details item-title="dictName"
                                    item-value="dictValue" label="学生状态" variant="outlined" />
                            </v-col>
                            <v-col cols="12" md="3">
                                <v-select v-model="queryParams.studentQP!.gender_EQ" :items="dict['gender']" clearable
                                    density="compact" hide-details item-title="dictName" item-value="dictValue"
                                    label="学生性别" variant="outlined" />
                            </v-col>
                            <v-col cols="12" md="3">
                                <v-text-field v-model="queryParams.studentQP!.school_LIKE" clearable density="compact"
                                    hide-details label="学校名称" placeholder="输入学校名称" prepend-inner-icon="mdi-school"
                                    variant="outlined" />
                            </v-col>
                            <v-col cols="12" md="3">
                                <v-text-field v-model="queryParams.studentQP!.className_EQ" clearable density="compact"
                                    hide-details label="班级名称" placeholder="输入班级名称"
                                    prepend-inner-icon="mdi-google-classroom" variant="outlined" />
                            </v-col>
                            <v-col cols="12" md="3">
                                <v-select v-model="queryParams.studentQP!.educationType_EQ"
                                    :items="dict['education_type']" clearable density="compact" hide-details
                                    item-title="dictName" item-value="dictValue" label="教育类型" variant="outlined" />
                            </v-col>
                        </v-row>
                    </div>

                    <!-- 时间范围查询 -->
                    <div class="mb-4">
                        <h4 class="text-subtitle-1 font-weight-medium mb-3 text-primary">
                            <v-icon class="mr-2" size="16">mdi-calendar-range</v-icon>
                            时间范围
                        </h4>
                        <v-row>
                            <v-col cols="12" md="3">
                                <v-text-field v-model="queryParams.createTime_GE" clearable density="compact"
                                    hide-details label="创建时间开始" type="date" variant="outlined" />
                            </v-col>
                            <v-col cols="12" md="3">
                                <v-text-field v-model="queryParams.createTime_LE" clearable density="compact"
                                    hide-details label="创建时间结束" type="date" variant="outlined" />
                            </v-col>
                            <v-col cols="12" md="3">
                                <v-text-field v-model="queryParams.establishDate_GE" clearable density="compact"
                                    hide-details label="建立日期开始" type="date" variant="outlined" />
                            </v-col>
                            <v-col cols="12" md="3">
                                <v-text-field v-model="queryParams.establishDate_LE" clearable density="compact"
                                    hide-details label="建立日期结束" type="date" variant="outlined" />
                            </v-col>
                        </v-row>
                    </div>
                </v-card-text>
            </v-expand-transition>

            <!-- 数据表格 -->
            <v-data-table v-model="selectRows" :headers="headers" :items="dataList" :items-length="total"
                :items-per-page="queryParams.pageSize" :loading="loading" :page="queryParams.pageNo" item-value="id"
                show-select @update:page="handlePageChange" @update:items-per-page="handlePageSizeChange"
                @update:model-value="setSelectRows">
                <!-- 家长信息 -->
                <template #item.customerInfo="{ item }">
                    <div class="d-flex align-center">
                        <v-avatar class="mr-3" color="primary" size="40">
                            <span class="text-white">{{ item.customerName?.charAt(0) || '客' }}</span>
                        </v-avatar>
                        <div>
                            <div class="font-weight-bold">{{ item.customerName || '未设置' }}</div>
                            <div class="text-caption text-grey-darken-1">
                                <v-icon class="mr-1" size="12">mdi-phone</v-icon>
                                {{ item.customerPhone || '无手机号' }}
                            </div>
                        </div>
                    </div>
                </template>

                <!-- 学生信息 -->
                <template #item.studentInfo="{ item }">
                    <div v-if="item.studentName" class="d-flex align-center">
                        <v-avatar class="mr-3" color="success" size="40">
                            <span class="text-white">{{ item.studentName?.charAt(0) }}</span>
                        </v-avatar>
                        <div>
                            <div class="font-weight-bold">{{ item.studentName }}</div>
                            <div class="text-caption text-grey-darken-1">
                                <v-icon class="mr-1" size="12">mdi-school</v-icon>
                                {{ getDictLabel(item.studentGrade, 'student_grade') || '未设置年级' }}
                            </div>
                        </div>
                    </div>
                    <div v-else class="text-center">
                        <v-chip color="grey" size="small" variant="outlined">
                            <v-icon size="16" start>mdi-account-off</v-icon>
                            暂无学生
                        </v-chip>
                    </div>
                </template>

                <!-- 关系信息 -->
                <template #item.relationInfo="{ item }">
                    <div class="text-center">
                        <v-chip :color="getDictColor(item.relationType, 'relation_type')" class="mb-1" size="small"
                            variant="flat">
                            {{ getDictLabel(item.relationType, 'relation_type') }}
                        </v-chip>
                        <br />
                        <v-chip v-if="item.isPrimary === '1'" color="primary" size="x-small" variant="outlined">
                            <v-icon size="12" start>mdi-star</v-icon>
                            主联系人
                        </v-chip>
                    </div>
                </template>

                <!-- 来源渠道 -->
                <template #item.sourceChannel="{ item }">
                    <div class="text-center">
                        <v-chip v-if="item.sourceChannel" color="info" size="small" variant="outlined">
                            <v-icon size="12" start>mdi-source-branch</v-icon>
                            {{ getChannelLabel(item.sourceChannel) }}
                        </v-chip>
                        <span v-else class="text-grey-lighten-1">-</span>
                    </div>
                </template>

                <!-- 客户状态 -->
                <template #item.customerStatus="{ item }">
                    <v-chip :color="getDictColor(item.customerStatus, 'customer_status')" size="small" variant="flat">
                        {{ getDictLabel(item.customerStatus, 'customer_status') || '未设置' }}
                    </v-chip>
                </template>

                <!-- 学生状态 -->
                <template #item.studentStatus="{ item }">
                    <v-chip v-if="item.studentStatus" :color="getDictColor(item.studentStatus, 'student_status')"
                        size="small" variant="flat">
                        {{ getDictLabel(item.studentStatus, 'student_status') }}
                    </v-chip>
                    <span v-else class="text-grey-lighten-1">-</span>
                </template>

                <!-- 客户详细信息 -->
                <template #item.customerDetails="{ item }">
                    <div class="text-body-2">
                        <div v-if="item.customerEmail" class="mb-1">
                            <v-icon class="mr-1" size="12">mdi-email</v-icon>
                            {{ item.customerEmail }}
                        </div>
                        <div v-if="item.customerAddress" class="mb-1">
                            <v-icon class="mr-1" size="12">mdi-map-marker</v-icon>
                            {{ item.customerAddress }}
                        </div>
                        <div v-if="item.customerTags">
                            <v-icon class="mr-1" size="12">mdi-tag</v-icon>
                            {{ item.customerTags }}
                        </div>
                    </div>
                </template>

                <!-- 操作列 -->
                <template #item.actions="{ item }">
                    <div class="d-flex gap-1">
                        <v-btn color="info" icon="mdi-eye" size="small" title="查看详情" variant="text"
                            @click="handleViewDetails(item)" />
                        <v-btn color="primary" icon="mdi-pencil" size="small" title="编辑" variant="text"
                            @click="handleEdit(item)" />
                        <v-btn color="error" icon="mdi-delete" size="small" title="删除" variant="text"
                            @click="handleDelete(item)" />
                    </div>
                </template>
            </v-data-table>
        </v-card>

        <!-- 编辑对话框 -->
        <CustomerStudentRelationManagementEdit ref="editRef" @fetch-data="fetchData" />

        <!-- 详情查看对话框 -->
        <CustomerStudentRelationDetailDialog ref="detailRef" />

        <!-- 批量添加关系对话框 -->
        <CustomerStudentRelationAdd ref="addRelationRef" @fetch-data="fetchData" />

        <!-- 文件上传对话框 -->
        <v-dialog v-model="importDialog" max-width="600px">
            <v-card>
                <v-card-title>
                    <span class="text-h6">导入Excel</span>
                </v-card-title>
                <v-card-text>
                    <v-file-input v-model="uploadFile" accept=".xlsx,.xls" label="选择Excel文件" placeholder="点击选择文件"
                        prepend-icon="mdi-file-excel" show-size variant="outlined" />
                </v-card-text>
                <v-card-actions>
                    <v-spacer />
                    <v-btn color="grey-darken-1" variant="text" @click="importDialog = false"> 取消</v-btn>
                    <v-btn color="primary" variant="text" @click="handleImportExcel"> 确定导入</v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>
    </v-container>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue';
import {
    getListWithDetails,
    doDelete,
    doDeleteAll,
    doExportExcel,
    doImportExcel,
    doDownloadTemplate,
    type CustomerStudentRelationModel,
    type CustomerStudentRelationQueryParams,
    type ApiResponse,
    type PageResult
} from '@/api/customer/customerrelation/CustomerStudentRelationManagementApi';
import CustomerStudentRelationManagementEdit from './components/CustomerStudentRelationManagementEdit.vue';
import CustomerStudentRelationDetailDialog from './components/CustomerStudentRelationDetailDialog.vue';
import CustomerStudentRelationAdd from './components/CustomerStudentRelationAdd.vue';
import { getDictListSync } from '@/utils/dict';
import { useMessage } from '@/composables/useMessage';
import { getChannelListSync } from '@/utils/channel';

const { success: showSuccess, error: showError } = useMessage();

// 基础数据
const loading = ref(false);
const dataList = ref<CustomerStudentRelationModel[]>([]);
const total = ref(0);
const selectRows = ref<string[]>([]);
const editRef = ref();
const detailRef = ref();
const addRelationRef = ref();
const importDialog = ref(false);
const uploadFile = ref<File[]>([]);
const showMoreQuery = ref(false);

// 查询参数
const queryParams = reactive<CustomerStudentRelationQueryParams>({
    pageNo: 1,
    pageSize: 10,
    customerQP: {},
    studentQP: {}
});

// 字典数据
const dict = reactive({
    relation_type: [] as any[],
    yes_no: [] as any[],
    customer_type: [] as any[],
    customer_status: [] as any[],
    student_grade: [] as any[],
    student_status: [] as any[],
    source_channel: [] as any[],
    relation_status: [] as any[],
    gender: [] as any[],
    education_type: [] as any[]
});

// 渠道数据
const channels = reactive({
    list: [] as any[]
});

// 表格列定义
const headers = computed(() => [
    {
        title: '家长信息',
        key: 'customerInfo',
        sortable: false,
        width: 200
    },
    {
        title: '学生信息',
        key: 'studentInfo',
        sortable: false,
        width: 200
    },
    {
        title: '关系',
        key: 'relationInfo',
        sortable: false,
        width: 120
    },
    {
        title: '来源渠道',
        key: 'sourceChannel',
        sortable: false,
        width: 120
    },
    {
        title: '详细信息',
        key: 'customerDetails',
        sortable: false,
        width: 250
    },
    {
        title: '创建时间',
        key: 'createTime',
        sortable: false,
        width: 150
    },
    {
        title: '操作',
        key: 'actions',
        sortable: false,
        width: 120
    }
]);

// 获取数据
async function fetchData() {
    loading.value = true;
    try {
        const { data }: ApiResponse<PageResult<CustomerStudentRelationModel>> = await getListWithDetails(queryParams);
        if (data) {
            dataList.value = data.rows || [];
            total.value = data.total || 0;
        }
    } catch (error) {
        console.error('Failed to fetch data:', error);
        showError('数据获取失败');
    } finally {
        loading.value = false;
    }
}

// 重置查询
function resetQuery() {
    Object.assign(queryParams, {
        pageNo: 1,
        pageSize: 10,

        // 关系信息
        relationType_EQ: undefined,
        isPrimary_EQ: undefined,
        sourceChannel_EQ: undefined,
        relationStatus_EQ: undefined,

        // 时间范围
        createTime_GE: undefined,
        createTime_LE: undefined,
        establishDate_GE: undefined,
        establishDate_LE: undefined,

        createBy_EQ: undefined,

        // 嵌套查询参数
        customerQP: {},
        studentQP: {}
    });
    fetchData();
}

// 切换更多查询
function toggleMoreQuery() {
    showMoreQuery.value = !showMoreQuery.value;
}

// 分页处理
function handlePageChange(page: number) {
    queryParams.pageNo = page;
    fetchData();
}

function handlePageSizeChange(size: number) {
    queryParams.pageSize = size;
    queryParams.pageNo = 1;
    fetchData();
}

// 选择处理
function setSelectRows(selected: string[]) {
    selectRows.value = selected;
}

// 查看详情
function handleViewDetails(row: CustomerStudentRelationModel) {
    detailRef.value?.showDetail(row);
}

// 新增
function handleAdd() {
    editRef.value?.showEdit();
}

// 批量添加关系
function handleAddRelation() {
    addRelationRef.value?.show();
}

// 编辑
function handleEdit(row: CustomerStudentRelationModel) {
    editRef.value?.showEdit(row);
}

// 删除
async function handleDelete(row: CustomerStudentRelationModel) {
    if (!confirm(`确定要删除这条客户关系记录吗？`)) return;

    try {
        const { msg } = await doDelete({ id: row.id! });
        showSuccess(msg || '删除成功');
        fetchData();
    } catch (error) {
        console.error('Delete failed:', error);
        showError('删除失败');
    }
}

// 批量删除
async function handleDeleteBatch() {
    if (!selectRows.value.length) {
        showError('请选择要删除的记录');
        return;
    }

    if (!confirm(`确定要删除选中的 ${selectRows.value.length} 条记录吗？`)) return;

    try {
        const { msg } = await doDeleteAll({ ids: selectRows.value.join(',') });
        showSuccess(msg || '批量删除成功');
        selectRows.value = [];
        fetchData();
    } catch (error) {
        console.error('Batch delete failed:', error);
        showError('批量删除失败');
    }
}

// 导出
async function handleExport() {
    try {
        await doExportExcel(queryParams);
        showSuccess('导出成功');
    } catch (error) {
        console.error('Export failed:', error);
        showError('导出失败');
    }
}

// 导入
function handleImport() {
    importDialog.value = true;
}

// 执行导入
async function handleImportExcel() {
    if (!uploadFile.value.length) {
        showError('请选择要导入的文件');
        return;
    }

    try {
        const formData = new FormData();
        formData.append('file', uploadFile.value[0]);

        const { msg } = await doImportExcel(formData as any);
        showSuccess(msg || '导入成功');
        importDialog.value = false;
        uploadFile.value = [];
        fetchData();
    } catch (error) {
        console.error('Import failed:', error);
        showError('导入失败');
    }
}

// 下载模板
async function handleDownloadTemplate() {
    try {
        await doDownloadTemplate();
        showSuccess('模板下载成功');
    } catch (error) {
        console.error('Download template failed:', error);
        showError('模板下载失败');
    }
}

// 字典工具函数
function getDictLabel(value: any, dictType: string): string {
    const dictList = dict[dictType as keyof typeof dict] as any[];
    const item = dictList?.find((item) => item.dictValue === value);
    return item?.dictName || value;
}

function getDictColor(value: any, dictType: string): string {
    const colors = ['primary', 'success', 'warning', 'error', 'info', 'purple', 'pink', 'indigo'];
    const dictList = dict[dictType as keyof typeof dict] as any[];
    const index = dictList?.findIndex((item) => item.dictValue === value) || 0;
    return colors[index % colors.length];
}

// 渠道工具函数
function getChannelLabel(channelId: any): string {
    const channel = channels.list.find((item) => item.id === channelId);
    return channel?.channelName || channelId;
}

// 初始化字典数据
function initDict() {
    dict['relation_type'] = getDictListSync('relation_type') || [];
    dict['yes_no'] = getDictListSync('yes_no') || [];
    dict['customer_type'] = getDictListSync('customer_type') || [];
    dict['customer_status'] = getDictListSync('customer_status') || [];
    dict['student_grade'] = getDictListSync('student_grade') || [];
    dict['student_status'] = getDictListSync('student_status') || [];
    dict['source_channel'] = getDictListSync('source_channel') || [];
    dict['relation_status'] = getDictListSync('relation_status') || [];
    dict['gender'] = getDictListSync('gender') || [];
    dict['education_type'] = getDictListSync('education_type') || [];
}

// 初始化渠道数据
function initChannels() {
    channels.list = getChannelListSync() || [];
}

// 生命周期
onMounted(() => {
    initDict();
    initChannels();
    fetchData();
});
</script>

<style lang="scss" scoped>
.gap-2 {
    gap: 8px;
}

.gap-1 {
    gap: 4px;
}

// 表格样式优化
:deep(.v-data-table) {
    .v-data-table__td {
        padding: 8px 16px;
    }

    .v-avatar {
        border: 2px solid rgba(255, 255, 255, 0.8);
    }
}

// 卡片标题样式
.v-card-title {
    .v-icon {
        color: white !important;
    }
}
</style>
